package org.neframework.webtest.action_rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.neframework.webtest.base.BaseController;
import org.neframework.webtest.model.t_fk_file;
import org.neframework.webtest.util.file.FileTools;

import com.tmsps.neframework.mvc.annotation.Controller;
import com.tmsps.neframework.mvc.annotation.RequestMapping;
import com.tmsps.neframework.mvc.annotation.RequestMappingRest;
import com.tmsps.neframework.mvc.annotation.ResponseBody;

@Controller
@RequestMapping("/rest")
public class UploadController extends BaseController {

	@RequestMapping("/upload")
	@ResponseBody
	public Map<String, Object> upload() throws FileUploadException {
		resp.setCharacterEncoding("utf-8");

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = req.getServletContext();
		File repository = (File) servletContext
				.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = upload.parseRequest(req);
		Iterator<FileItem> iter = items.iterator();

		t_fk_file tf = null;
		while (iter.hasNext()) {
			FileItem item = iter.next();

			if (item.isFormField()) {
				// 非文件上传字段
				continue;
			} else {
				tf = FileTools.processUploadedFile(req.getRealPath("/")
						+ File.separator + "data" + File.separator, item, oc);
			}
		}
		if (tf != null) {
			// 发送保存结果
			String url = req.getContextPath() + "/rest/download/" + tf.getKid()
					+ ".htm";

			result.put("success", true);
			result.put("file_id", tf.getKid());
			result.put("url", url);
			result.put("file_name", tf.getFile_name());
			result.put("content_type", tf.getContent_type());

		} else {
			result.put("success", false);
		}
		return result;
	}

	@RequestMapping("download")
	@RequestMappingRest("/download/([\\w-]{10,})")
	public void download(String file_id) throws Exception {
		FileInputStream fis = null;

		t_fk_file file = (t_fk_file) oc.findObjById(file_id, t_fk_file.class);

		try {
			String filename = file.getFile_name();

			File f = new File(req.getRealPath("/") + File.separator + "data"
					+ File.separator + file.getFolder(),
					file.getNew_file_name());
			if (!f.exists()) {
				f = new File(req.getRealPath("/") + File.separator
						+ "style/cp/img/", "file404.jpg");
				filename = "file404.jpg";
			}

			resp.setContentType("application/x-msdownload;");
			resp.setHeader("Content-disposition", "attachment; filename=\""
					+ new String(filename.getBytes("utf-8"), "ISO8859-1")
					+ "\"");
			resp.setHeader("Content-Length", f.length() + "");

			OutputStream os = resp.getOutputStream();

			fis = new FileInputStream(f);
			byte[] buff = new byte[2048];
			int bytesRead = -1;

			while (-1 != (bytesRead = fis.read(buff, 0, buff.length))) {
				os.write(buff, 0, bytesRead);
			}
			os.flush();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null)
				fis.close();

		}
	}
}
